import axiosInstance from "./http";
import qs from "qs";

import { Message } from "element-ui";
import { MessageBox } from "element-ui";

let map = {
  "0": "请求失败",
  "1": "请求成功",
  "100": "token失效"
};

const utils = {
  // 报错信息匹配
  error: function(code) {
    return map[code];
  },

  // get 请求
  get(url, params = {}) {
    return new Promise((resolve, reject) => {
      axiosInstance.get(url, { params }).then(
        res => {
          // 接口返回就用返回的 msg      code 1: 成功  0：失败  100：token失效
          if (res.data.code == 1) {
            resolve(res.data);
          } else if (res.data.code == 200) {
            Message({
              message: res.data.msg || "暂无权限哦！",
              type: "error",
              showClose: true,
              duration: 5000
            });
            resolve(res.data);
          } else if (res.data.code === 110) {
            let data = res.data.error;
            let arrName = [];
            let arrValue = [];
            let errorInfo = [];
            let errorValue = "";
            for (let i in data) {
              arrName.push(i);
              arrValue.push(data[i]);
            }
            for (let i = 0; i < arrName.length; i++) {
              errorInfo[i] = "";
              for (let j = 0; j < arrValue[i].length; j++) {
                console.log(arrValue[i][j]);
                errorInfo[i] += arrValue[i][j] + "；";
              }
              errorValue += errorInfo[i];
            }
            console.log(errorValue);
            MessageBox.alert(
              `<p style="width: 380px; font-size: 16px;">${errorValue}</p>`,
              {
                customClass: "ajax-error",
                showConfirmButton: true,
                dangerouslyUseHTMLString: true,
                title: "错误提示"
              }
            );
          } else if (res.data.code === 111) {
            // Message({
            //   message: '请先进行PT测试',
            //   type: 'error',
            //   showClose: true,
            //   duration: 5000
            // });
            // reject();
            resolve(res.data);
          } else {
            Message({
              message: res.data.msg || this.error(res.data.code),
              type: "error",
              showClose: true,
              duration: 5000
            });
            
            if (res.data.code == 100) {
              sessionStorage.clear();
              location.href = "/login";
            }
            reject();

          }
        },
        err => {
          if (err.message === "Request failed with status code 504") {
            Message({
              message: `网络连接失败，请检查网络设置`,
              type: "warning",
              showClose: true,
              duration: 5000
            });
          } else {
            Message({
              message: `请求失败，接口地址：${url}，原因：${err.message}`,
              type: "error",
              showClose: true,
              duration: 5000
            });
          }
          reject(err);
        }
      );
    });
  },

  // post 请求  ---  提交数据
  post(url, data = {}) {
    return new Promise((resolve, reject) => {
      axiosInstance.post(url, qs.stringify(data)).then(
        res => {
          // 接口返回就用返回的 msg
          if (res.data.code == 1) {
            resolve(res.data);
          } else if (res.data.code == 200) {
            Message({
              message: res.data.msg || "暂无权限哦！",
              type: "error",
              showClose: true,
              duration: 5000
            });
            resolve(res.data);
          } else if (res.data.code === 110) {
            let data = res.data.error;
            let arrName = [];
            let arrValue = [];
            let errorInfo = [];
            let errorValue = "";
            for (let i in data) {
              arrName.push(i);
              arrValue.push(data[i]);
            }
            for (let i = 0; i < arrName.length; i++) {
              errorInfo[i] = "";
              for (let j = 0; j < arrValue[i].length; j++) {
                console.log(arrValue[i][j]);
                errorInfo[i] += arrValue[i][j] + "；";
              }
              errorValue += errorInfo[i];
            }
            console.log(errorValue);
            MessageBox.alert(
              `<p style="width: 380px; font-size: 16px;">${errorValue}</p>`,
              {
                customClass: "ajax-error",
                showConfirmButton: true,
                dangerouslyUseHTMLString: true,
                title: "错误提示"
              }
            );
            reject();
            // this.$confirm(`<p style="width: 380px; font-size: 16px; text-align: center;">${errorValue}</p>`, '错误提示', {
            // dangerouslyUseHTMLString: true,
            // showCancelButton: false
            // })
            // Message({
            //     message: res.data.msg || this.error(res.data.code),
            //     type: 'error',
            //     showClose: true,
            //     duration: 5000
            // });
          } else {
            Message({
              message: res.data.msg || this.error(res.data.code),
              type: "error",
              showClose: true,
              duration: 5000
            });
            
            if (res.data.code == 100) {
              sessionStorage.clear();
              location.href = "/login";
            }
            reject();
            // resolve()
          }
        },
        err => {
          Message({
            message: `请求失败，接口地址：${url}，原因：${err.message}`,
            type: "error",
            showClose: true,
            duration: 5000
          });

          reject(err);
        }
      );
    });
  }
};
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

// 一维数组转二维数组
export function switchTwoArray(objArray) {
  let lenth = objArray.length;
  let colNum = 3;
  let rowNum =
    lenth % colNum == 0 ? lenth / colNum : Math.floor(lenth / colNum + 1);
  let copyArray = [];
  for (let i = 0; i < rowNum; i++) {
    copyArray.push(
      JSON.parse(
        JSON.stringify(objArray.slice(i * colNum, i * colNum + colNum))
      )
    );
  }
  return copyArray;
}

// 格式化时间
export const formatDate = {
  pad(num) {
    return Number(num) < 10 ? `0${num}` : num;
  },
  toStr(timestamp, formatStr = "YYYY-MM-DD HH:mm") {
    // 时间戳转字符串
    try {
      const sec = Number(timestamp);
      const dt = new Date(sec);
      const formatMap = {
        YYYY: dt.getFullYear(),
        MM: formatDate.pad(dt.getMonth() + 1),
        DD: formatDate.pad(dt.getDate()),
        HH: formatDate.pad(dt.getHours()),
        mm: formatDate.pad(dt.getMinutes()),
        ss: formatDate.pad(dt.getSeconds())
      };
      let final = formatStr;
      Object.keys(formatMap).forEach(key => {
        final = final.replace(new RegExp(key, "g"), formatMap[key]);
      });
      return final;
    } catch (error) {
      window.console.warn(error);
      return timestamp;
    }
  },
  toSec(str) {
    // 字符串转时间戳
    try {
      const dateObj = new Date(str);
      return dateObj.getTime();
    } catch (error) {
      window.console.warn(error);
      return str;
    }
  }
};

// obj 转 array
export function formatArray(obj) {
  let arrData = [];
  let keysData = Object.keys(obj);
  if (keysData.length) {
    keysData.map(item => {
      arrData.push({ value: item, label: obj[item] });
    });
  }
  return arrData;
}

// array 转 obj
export function formatObj(arr) {
  var obj = {};
  for (var i = 0; i < arr.length; i++) {
    obj[i] = arr[i];
  }

  return obj
}

export default utils;
